package Offer55;

import com.sun.source.tree.Tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author 23737
 * @time 2021.9.18
 * 二叉树的深度：
 * 输入一棵二叉树的根节点，求该树的深度。从根节点到叶节点依次经过的节点（含根、叶节点）形成树的一条路径，最长路径的长度为树的深度。
 */
public class Test {
    public static void main(String[] args) {

    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

/*使用百分数进行遍历*/
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        Queue<TreeNode> temp;
        queue.add(root);
        int count = 0;
        while (!queue.isEmpty()) {
            temp = new LinkedList<>();
            for (TreeNode t: queue
            ) {
                if (t.left != null){
                    temp.add(t.left);
                }
                if(t.right!=null){
                    temp.add(t.right);
                }
            }
            queue = temp;
            count++;
        }
        return count;
    }
}

/*层序遍历用这种写法我觉得更合适*/
class SolutionTwo {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int res = 0;
        while (!queue.isEmpty()) {
            res++;
            int n = queue.size();
            for (int i = 0; i < n; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
        }
        return res;
    }
}